<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { useUserStore } from '@/store'
import UniStorage from '@/utils/storage'
import Muni from '@/muni'

const userStore = useUserStore()

onLaunch(() => {
  console.log('App Launch')

  /* #ifdef H5 */
  loginH5()
  /* #endif */

  /* #ifdef MP */
  Muni.setAppInfo({
    appid: 'wx3d3aec330536235d',
    platform: 'mp-weixin',
  })
  loginMiniProgram()
  /* #endif */
})
onShow(() => {
  console.log('App Show')
})
onHide(() => {
  console.log('App Hide')
})

// 小程序登录
function loginMiniProgram() {
  const userInfo = UniStorage.getItem('userInfo')
  if (userInfo) {
    userStore.setUserInfo(userInfo)
    return
  }
  Muni.login().then((res) => {
    console.log(
      '%c用户信息',
      'border: 1px solid white;border-radius: 3px 0 0 3px;padding: 2px 5px;color: white;background-color: green;',
    )
    console.table(res)

    const userInfo = {
      appid: res.appid,
      openid: res.openid,
      unionid: res.unionid,
      uid: res.uid,
      session_id: res.session_id,
      session_key: res.session_key,
      nickname: res?.nickname || '',
      headimgurl: res?.headimgurl || '',
    }
    userStore.setUserInfo(userInfo)
    UniStorage.setItem('userInfo', userInfo)
  })
}
// H5登录
function loginH5() {
  window.mo.init({ appid: 'wx641ee49935391e3c', polyfill: true })
  window.mo.wxLogin.login({
    type: 'wechat',
    scope: 'profile',
    required: true,
    success: (res) => {
      console.log(
        '%c用户信息',
        'border: 1px solid white;border-radius: 3px 0 0 3px;padding: 2px 5px;color: white;background-color: green;',
      )
      console.table(res)
      userStore.setUserInfo({
        appid: res.appid,
        openid: res.openid,
        unionid: res.unionid,
        nickname: res.nickname,
        headimgurl: res.headimgurl,
        session_id: res?.session_id || '',
        session_key: res?.session_key || '',
        uid: res?.uid || '',
      })
    },
    fail: (err) => {
      console.log('err --->', err)
    },
  })
}
</script>

<style lang="scss"></style>
